<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Magnifier</title>
  <style>
    html,body{
      width: 100%;
      margin: 0;
    }

    #container {
      position: relative;
      max-width: 700px;
      margin: 0 auto;
    }

    #canvas {
      width: 100%; 
      height: auto; 
    }

    #magnifier {
      position: absolute;
      border: 2px solid black;
      border-radius: 50%;
      pointer-events: none; /* 禁用鼠标事件 */
      transform: translate(-50%, -50%); /* 使放大镜居中 */
      display: none; /* 默认隐藏 */
    }
  </style>
</head>

<body>
  <div id="container">
    <canvas id="canvas"></canvas>
    <canvas id="magnifier"></canvas>
  </div>
  <script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const magnifier = document.getElementById('magnifier');
    const magnifierCtx = magnifier.getContext('2d');
    const img = new Image();
    img.src = '1.jpg'; // 替换为你自己的图片URL

    img.onload = () => {
      // 初始绘制图片
      resizeCanvas();
      window.addEventListener('resize', resizeCanvas);

      function resizeCanvas() {
        // 获取父容器的宽度和高度
        const rect = canvas.getBoundingClientRect();
        canvas.width = rect.width;
        canvas.height = rect.width * (img.height / img.width); // 保持图像比例

        // 清除画布并重新绘制图像
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      }

      canvas.addEventListener('mousemove', (e) => {
        const rect = canvas.getBoundingClientRect();
      
        // 获取鼠标在canvas中的坐标
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        // 显示放大镜
        magnifier.style.display = 'block';
        magnifier.style.left = `${x}px`;
        magnifier.style.top = `${y}px`;

        // 放大镜的半径
        const magnifierRadius = 100;
        // 放大倍数
        const zoom = 1  ;

        // 清除放大镜画布
        magnifierCtx.clearRect(0, 0, magnifier.width, magnifier.height);

        const scaleX = img.width / canvas.width;
        const scaleY = img.height / canvas.height;

        magnifier.width = magnifierRadius * 2;
        magnifier.height = magnifierRadius * 2;

        magnifierCtx.drawImage(
          img,
          (x * scaleX) - magnifierRadius / zoom,
          (y * scaleY) - magnifierRadius / zoom,
          magnifierRadius * 2 / zoom,
          magnifierRadius * 2 / zoom,
          0,
          0,
          magnifier.width,
          magnifier.height
        );
        
        // 绘制放大镜边框
        magnifierCtx.beginPath();
        magnifierCtx.arc(magnifierRadius, magnifierRadius, magnifierRadius, 0, Math.PI * 2);
        magnifierCtx.stroke();
      });

      canvas.addEventListener('mouseleave', () => {
        // 隐藏放大镜
        magnifier.style.display = 'none';
      });
    };
  </script>
</body>

</html>
